package com.xxx.routing;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * Rabbit MQ使用场景四：根据路由键发布和订阅消息
 * 
 * @author guweiqiang
 * 2018年6月13日
 */
public class RoutingPublisher {
	
//	private static final String HOST = "localhost";
	private static final String EXCHANGE_NAME = "amq.direct"; // amq.direct是自带的exchanger
	// 路由关键字
    private static final String[] ROUTING_KEYS = new String[]{"info", "warning", "error"};

	public static void main(String[] args) throws IOException, TimeoutException {
		// 1.创建连接工厂，并设置工厂相关属性
		ConnectionFactory factory = new ConnectionFactory();
//		factory.setHost(HOST); // 默认为localhost
		
		// 2.创建一个连接
		Connection connection = factory.newConnection();
		
		// 3.创建一个通道
		Channel channel = connection.createChannel();
		
		// 4.声明交换机
		channel.exchangeDeclare(EXCHANGE_NAME, "direct", true);  // 交换机类型为：direct
		// direct 直接交换器，工作方式类似于单播，Exchange会将消息发送完全匹配ROUTING_KEY的Queue
		
		// 5.发送消息（分别往这些路由key的交换机的发送消息）
		for(String routingKey : ROUTING_KEYS) {
			for(int i=1; i<3; i++) {
				String message = "hello rabbit mq:" + i + routingKey;
				// 按路由关键字分发
				channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes()); 
				System.out.println("send message:" + message);
			}
		}
		
		// 6.关闭连接
		channel.close();
        connection.close();
	}

}
